from flask import Blueprint, request, jsonify, session, render_template, redirect, url_for
import requests
from flask_login import login_required, current_user

# 创建蓝图
pansou_bp = Blueprint('pansou', __name__, url_prefix='/pansou')

# 网盘搜索页面
@pansou_bp.route('/')
@login_required
def index():
    return render_template('pansou.html', username=current_user.username)

# 获取热搜列表
@pansou_bp.route('/hot_keywords', methods=['GET'])
@login_required
def get_hot_keywords():
    try:
        # 设置请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        }
        # 调用热搜列表API
        response = requests.get('https://api.hunhepan.com/v1/extab/list_all', headers=headers, timeout=5)
        response.raise_for_status()
        
        data = response.json()
        return jsonify(data)
    except requests.exceptions.RequestException as e:
        return jsonify({'error': f'API请求失败: {str(e)}'}), 500
    except Exception as e:
        return jsonify({'error': f'处理请求时发生错误: {str(e)}'}), 500

# 网盘搜索API
@pansou_bp.route('/search', methods=['POST'])
@login_required
def search():
    # 获取搜索参数
    data = request.json
    if not data or 'q' not in data:
        return jsonify({'error': '未提供搜索查询'}), 400
    
    try:
        # 构建请求数据
        search_data = {
            'q': data.get('q', ''),
            'page': data.get('page', 1),
            'size': data.get('size', 10),
            'time': data.get('time', ''),
            'type': data.get('type', ''),
            'exact': data.get('exact', True)
        }
        
        # 设置请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        }
        # 调用搜索API
        response = requests.post(
            'https://hunhepan.com/open/search/disk', 
            json=search_data,
            headers=headers,
            timeout=5
        )
        response.raise_for_status()
        
        result = response.json()
        return jsonify(result)
    except requests.exceptions.RequestException as e:
        return jsonify({'error': f'API请求失败: {str(e)}'}), 500
    except Exception as e:
        return jsonify({'error': f'处理请求时发生错误: {str(e)}'}), 500 